package com.tsinghuabigdata.edu.ddmath.module.ddwork;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.camera.CameraPreviewCallBack;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.camera.DetectListener;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.view.FixedPiontView;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.XBookUtils;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.view.MoveImageView;
import com.tsinghuabigdata.edu.ddmath.util.AppLog;
import com.tsinghuabigdata.edu.ddmath.util.ToastUtils;
import com.tsinghuabigdata.edu.ddmath.util.WindowUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class DDCameraActivity extends Activity implements View.OnClickListener, DetectListener {

    //上面提示框区域
    private RelativeLayout tipsLayout;

    //
    private RelativeLayout mainLayout;

    //
    private SurfaceView mSurfaceView;

    //闪光灯
    private ImageView mFlashLedView;
    //对焦效果
    private MoveImageView mFocusImageView;

    //定位框
    private Drawable detechDrawble;
    private FixedPiontView lefttopFixedView;
    private FixedPiontView righttopFixedView;
    private FixedPiontView leftbottomFixedView;

    private Context mContext;
    private Activity mActivity;
    private DetectListener mDetectListener;
    private Camera camera = null;

    private boolean autofocus = false;

    private boolean bStartPreview = false;
    private boolean exit = true;
    private static final Object lock = new Object();;
    
    private boolean bAutoFocus = false;
    private boolean bCameraReady = false;
    //private boolean onlyFocuse = false;
    private int offset_margin = 0;

    //private final static int MODE_PICS = 100;    //相册返回
    private final static int MODE_EDIT = 101;    //图片编辑界面返回

    //传递过来的参数
    private String workId;        //作业ID
    private int    pageIndex;     //页序号

    //
    private int centerScreenX;
    private int centerScreenY;
    //隐藏虚拟键后的宽高
    private int mScreenWidth;
    private int mScreenHeight;

    private CameraPreviewCallBack mPreviewCallBack;
    private boolean bQuit = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setTheme( R.style.Theme_Custom_AppCompat );
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        //设置全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //hideNavigationBar();

        setContentView(R.layout.activity_ddwork_camera);

        mContext = this;
        mActivity = this;
        bStartPreview = false;
        mDetectListener = this;

        Point point = new Point();
        getWindowManager().getDefaultDisplay().getRealSize(point);
        mScreenWidth = point.x;
        mScreenHeight = point.y;

        mPreviewCallBack = new CameraPreviewCallBack( mContext );
        if( !parseIntent() ){
            ToastUtils.show( this, "参数错误", Toast.LENGTH_SHORT );
            return;
        }
        initView();

        initAutofocus();

        //
        startSetParamThread();

    }

    public void hideNavigationBar()
    {
        int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                | View.SYSTEM_UI_FLAG_FULLSCREEN; // hide status bar

        if( android.os.Build.VERSION.SDK_INT >= 19 ){
            uiFlags |= 0x00001000;    //SYSTEM_UI_FLAG_IMMERSIVE_STICKY: hide navigation bars - compatibility: building API level is lower thatn 19, use magic number directly for higher API target level
        } else {
            uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }
        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
    }


    @Override
    protected void onPause() {
        super.onPause();

        mSensorManager.unregisterListener(mSensorListener);

        if( camera!=null ) {
            camera.stopPreview();
            camera.setPreviewCallback( null );
        }
    }


    @Override
    protected void onResume() {
        super.onResume();

        hideNavigationBar();

        mFocusImageView.setVisibility( View.INVISIBLE );
        bAutoFocus = false;

        mSensorManager.registerListener(mSensorListener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
        mSensorManager.registerListener(mSensorListener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY),
                SensorManager.SENSOR_DELAY_NORMAL);
        mSensorManager.registerListener(mSensorListener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_NORMAL);

        AppLog.i(" PreviewCallback camera = " + camera );
        if( camera!=null ) {
            camera.startPreview();
            camera.setPreviewCallback( mPreviewCallBack );
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {// 屏幕触摸事件

        if (event.getAction() == MotionEvent.ACTION_DOWN) {// 按下时自动对焦
            autofocus = true;
        }
        if (event.getAction() == MotionEvent.ACTION_UP && autofocus ) {// 放开后拍照
            try {
                Rect rect = new Rect();
                mainLayout.getGlobalVisibleRect( rect );
                if( rect.contains( (int)event.getRawX(), (int)event.getRawY()) )
                    autoFocus( true, event.getX() - offset_margin, event.getY()-tipsLayout.getHeight() );
            } catch (Exception e) {
                AppLog.d( e.toString() );
            }
            autofocus = false;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mPreviewCallBack.stopDetechAynscTask();

        if (camera != null) {
            camera.release();
            camera = null;
        }
        bQuit = true;
        //cameraInstance = false;
    }

    @Override
    public void onClick(View v) {

        switch ( v.getId() ){

            case R.id.ddwork_layout_cameraledbtn:{       //手电筒
                int mode = getCameraFlashMode();
                mode = (mode+1)%2;        //改变
                setFlashMode( mode );
                break;
            }
//            case R.id.ddwork_iv_photobtn:{       //相册
//                Intent intent = new Intent(Intent.ACTION_PICK, null);
//                intent.setDataAndType( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*" );
//                startActivityForResult( intent, MODE_PICS );
//                break;
//            }

//            case R.id.ddwork_camera_enter:{       //拍摄
//                while( !bCameraReady ){
//                    SystemClock.sleep(50);
//                }
//
//                autoFocus( false, centerScreenX, centerScreenY  );
//                break;
//            }

            case R.id.ddwork_layout_cameracancel:{       //取消
                finish();
                break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch( requestCode ) {
//            case MODE_PICS: {             //相册返回
//                if (resultCode == RESULT_OK) {
//                    try {
//                        Uri originalUri = data.getData();        //获得图片的uri
//
//                        String[] proj = {MediaStore.Images.Media.DATA};
//                        Cursor cursor = managedQuery(originalUri, proj, null, null, null);
//                        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//                        cursor.moveToFirst();
//                        String path = cursor.getString(column_index);
//
//                        startEditPhoto(path);
//                    } catch (Exception e) {
//                        AppLog.i(e.toString());
//                    }
//                }
//                break;
//            }
            case  MODE_EDIT:{
                if(data != null ) {
                    if (data.hasExtra("from")) {    //
                        bAutoFocus = false;
                        mPreviewCallBack.setRunStatus( false );

                        //状态恢复
                        detectResult( 0 );

                    } else if (data.hasExtra("close")) {     //通知关闭
                        finish();
                    }
                }
                break;
            }
            default:
                break;
        }
    }

    @Override
    public void detectResult( final int result) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                //100代表左上角,010代表右上角,001代表左下角
                if( (0x4&result) == 0x4){
                    lefttopFixedView.setFixedStatus( FixedPiontView.ST_FIXED );
                }else{
                    lefttopFixedView.setFixedStatus( FixedPiontView.ST_FIXING );
                }

                if( (0x2&result) == 0x2){
                    righttopFixedView.setFixedStatus( FixedPiontView.ST_FIXED );
                }else{
                    righttopFixedView.setFixedStatus( FixedPiontView.ST_FIXING );
                }

                if( (0x1&result) == 0x1){
                    leftbottomFixedView.setFixedStatus( FixedPiontView.ST_FIXED );
                }else{
                    leftbottomFixedView.setFixedStatus( FixedPiontView.ST_FIXING );
                }
            }
        });
    }

    @Override
    public void detectFile(String filepath) {

        AppLog.i(" DetechAynscTask filepath = " + filepath );

        Intent intent = new Intent(this, DDPreviewActivity.class);
        intent.putExtra( XBookUtils.IMAGE_TYPE, XBookUtils.TYPE_LOCAL );
        intent.putExtra( XBookUtils.IMAGE_HANDLE, filepath );

        intent.putExtra( DDWorkUtil.PAGEINDEX, pageIndex );
        intent.putExtra( DDWorkUtil.WORK_ID, workId );

        startActivityForResult(intent, MODE_EDIT);
    }

    @Override
    public void cameraRorate( int degree[] ){
        degree[0] = getCameraDegree();
    }

    //-------------------------------------------------------------------------------------------------
    private void initView() {

        centerScreenX = mScreenWidth / 2;
        centerScreenY = mScreenHeight / 2;

        detechDrawble = getResources().getDrawable( R.drawable.ic_correct );

        tipsLayout = (RelativeLayout)findViewById( R.id.ddwork_tips_layout );
        mainLayout = (RelativeLayout)findViewById( R.id.ddwork_mainLayout );

        mSurfaceView = (SurfaceView)findViewById( R.id.ddwork_camera_preview );

        //
        SurfaceHolder surfaceHolder = mSurfaceView.getHolder(); // Camera interface to instantiate components
        surfaceHolder.addCallback(surfaceCallback); // Add a callback for the SurfaceHolder

        LayoutParams params = new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT );
        mSurfaceView.setLayoutParams(params);

        RelativeLayout mFlashLedLayout = (RelativeLayout)findViewById( R.id.ddwork_layout_cameraledbtn );
        mFlashLedLayout.setOnClickListener(this);

        if( !getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH) ){
            mFlashLedLayout.setVisibility( View.GONE );     //没有闪光灯
        }

        //手电筒效果
        mFlashLedView = (ImageView) findViewById(R.id.ddwork_camera_flashimg);
        mFlashLedView.setImageResource(getImageFlashMode());

        //CameraGridView gridView = (CameraGridView)findViewById( R.id.ddwork_camera_gridview );
        //gridView.setPortFlag( true );

        int mode = getCameraFlashMode();
        setFlashMode( mode );

        mFocusImageView = (MoveImageView) findViewById(R.id.ddwork_iv_focusimg);

//        TextView photoTextView = (TextView)findViewById( R.id.ddwork_iv_photobtn );
//        photoTextView.setOnClickListener(this);

        RelativeLayout mCancelLayout = (RelativeLayout)findViewById(R.id.ddwork_layout_cameracancel);
        mCancelLayout.setOnClickListener( this );

        //RelativeLayout cameraEnterLayout = (RelativeLayout) findViewById(R.id.ddwork_camera_enter);
        //cameraEnterLayout.setOnClickListener(this);

        lefttopFixedView = (FixedPiontView)findViewById( R.id.ddwork_lefttop_fixpointview );
        righttopFixedView = (FixedPiontView)findViewById( R.id.ddwork_righttop_fixpointview );
        leftbottomFixedView = (FixedPiontView)findViewById( R.id.ddwork_leftbottom_fixpointview );
    }

    //根据显示情况，设置取景框高宽，及 定位框
    private void startSetParamThread(){
        new Thread(new Runnable() {
            @Override
            public void run() {

                while( true ){

                    SystemClock.sleep(50);
                    if( bQuit ) break;

                    if( tipsLayout.getHeight() == 0 || camera == null/* || !bAutoFocus */ )
                        continue;
                    //bAutoFocus = false;

                    //设置相机参数
                    Point point = new Point();
                    if( !setPicturePix( point ) ){

                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShort( mContext, "相机参数设置失败");
                            }
                        });
                        return;
                    }

                    //先判断 相机参数 与 屏幕的关系，调整surfaceView的边距
                    int camera_width = point.x;
                    int camera_height= point.y;

                    //  预览显示到屏幕的变化比例
                    float rate_w = mScreenWidth*1f / camera_width;         //  预览
                    float rate_h = mScreenHeight*1f / camera_height;       //

                    //final int camera_marginWidth = ( mScreenWidth - camera_width )/2;
                    //final int camera_marginHeight= ( mScreenHeight - camera_height )/2;
                    //AppLog.i(" DetechAynscTask set SurfaceView camera_marginWidth = " + camera_marginWidth + ",,, camera_marginHeight = " + camera_marginHeight );
//                    mActivity.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)mSurfaceView.getLayoutParams();
//                            layoutParams.setMargins( camera_marginWidth, camera_marginHeight, camera_marginWidth, camera_marginHeight );
//                            mSurfaceView.setLayoutParams( layoutParams );
//                        }
//                    });

                    //识别标志图最小宽度 图片宽度 + 8dp
                    int minImageWidth = detechDrawble.getIntrinsicWidth() + WindowUtils.dpToPixels(mContext,8);

                    // 调整拍照裁剪框的边距

                    //可用宽高
                    int usewidth = mScreenWidth - minImageWidth*2;
                    int useheight= mScreenHeight - tipsLayout.getHeight();

                    //裁剪框的目标宽高(变换比例)
                    int dstWidth = (int)((useheight * 210 * rate_w) / (297 * rate_h) );      //默认 高度撑满
                    int dstHeight= useheight;
                    if( dstWidth > usewidth ){
                        dstWidth = usewidth;                   //宽度撑满，
                        dstHeight= (int)((usewidth * 297 * rate_h) / (210 * rate_w) );
                    }

                    //计算上下 左右的偏移距离
                    int offset_width = ( mScreenWidth - dstWidth ) / 2;//     + camera_marginWidth;
                    int offset_height= ( useheight - dstHeight ) / 2;//   + camera_marginHeight;

                    AppLog.i(" DetechAynscTask set MainLayout offset_width = " + offset_width + ",,, offset_height = " + offset_height );

                    adjustViewPostion( offset_width,offset_height );

                    //裁剪框（相对surfaceView ）
                    Rect cropRect = new Rect();
                    cropRect.left = offset_width;
                    cropRect.top  = tipsLayout.getHeight();
                    cropRect.right= cropRect.left + dstWidth;
                    cropRect.bottom= cropRect.top + dstHeight;
                    //变换相对预览图的位置
                    cropRect.left = (int)(cropRect.left / rate_w);
                    cropRect.top = (int)(cropRect.top / rate_h);
                    cropRect.right = (int)(cropRect.right / rate_w);
                    cropRect.bottom = (int)(cropRect.bottom / rate_h);


                    //左上角 定位框 的 Rect    相对于裁剪框的位置
                    int left = WindowUtils.dpToPixels( mContext, 4 );
                    int top = WindowUtils.dpToPixels( mContext, 4 );
                    int width = WindowUtils.dpToPixels( mContext, 94 );
                    int height=width;

                    //变换相对预览图的位置
                    left = (int)(left / rate_w);
                    top = (int)(top / rate_h);
                    width = (int)(width / rate_w);
                    height = (int)(width / rate_h);

                    Rect fixRect = new Rect( left, top, left+width, top+height );

                    mPreviewCallBack.setData( cropRect, fixRect, mDetectListener, camera_width, camera_height );
                    break;
                }

            }
        }).start();
    }

    private boolean parseIntent(){

        Intent intent = getIntent();
        workId     = intent.getStringExtra( DDWorkUtil.WORK_ID );
        pageIndex  = intent.getIntExtra( DDWorkUtil.PAGEINDEX, -1 );

        return !(TextUtils.isEmpty(workId) || pageIndex < 0 );
    }

    //private OrientationEventListener mOrientationListener;
    private SensorEventListener mSensorListener;
    private SensorManager mSensorManager;
    private float mX = 0.0f;
    private float mY = 0.0f;
    private float mZ = 0.0f;
    private float mOrX = 0.0f;
    private float mOrY = 0.0f;
    private float mOrZ = 0.0f;
    private long lastTime = 0;  
    private long curTime = 0;  
    private Boolean isMove = false;    
    
    //根据重力感应自动对焦
    private void initAutofocus(){
            
        //
//        mOrientationListener = new OrientationEventListener(this) {
//            @Override
//            public void onOrientationChanged(int orientation) {
//                if (orientation == ORIENTATION_UNKNOWN) return;
//                
//                if (camera != null){
//                    //mPreview.onConfigurationChanged(null);
//                }
//            }
//        };

        mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        mSensorListener = new SensorEventListener() {
            
            @Override
            public void onSensorChanged(SensorEvent event) {
                if (event.sensor == null)
                    return;

                //获取当前时刻的毫秒数  
                curTime = System.currentTimeMillis();  
                //100毫秒检测一次  
                if ((curTime - lastTime) > 350) {
                    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
                        final float x = event.values[0];
                        final float y = event.values[1];
                        final float z = event.values[2];
                        final float px = Math.abs(mX - x);
                        final float py = Math.abs(mY - y);
                        final float pz = Math.abs(mZ - z);
                        
                        mX = x;
                        mY = y;
                        mZ = z;
                        float h = Math.max(Math.max(px, py), pz);//Math.max(px, py);
                        final float hz = (float) Math.abs(z - 9.81);
                        if ((h > 2.0f || (hz > 0.6f && pz > 0.8f))  && camera != null){
                           isMove = true;
                        } else {
                           if( camera != null && isMove)
                           {
                               isMove = false;
                               if(!bAutoFocus&&bCameraReady) {
                                   camera.autoFocus( null );
                               }
                           }
                        }
                    }
                    if(event.sensor.getType() == Sensor.TYPE_ORIENTATION)
                    {
                        final float x = event.values[0];
                        final float y = event.values[1];
                        final float z = event.values[2];
                        final float px = Math.abs(mOrX - x);
                        final float py = Math.abs(mOrY - y);
                        final float pz = Math.abs(mOrZ - z);
                        
                        mOrX = x;
                        mOrY = y;
                        mOrZ = z;
                        if (Math.max(Math.max(px, py), pz) > 30.0f && camera != null){
                               isMove = true;
                        }
                    }
                    
                    lastTime = curTime;  
                }
            }
            
            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
            }
        };
    }

    private void adjustViewPostion( final int offset_width, final int offset_height ){

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)mainLayout.getLayoutParams();
                layoutParams.setMargins( offset_width, 0, offset_width, offset_height*2 );
                mainLayout.setLayoutParams( layoutParams );

                offset_margin = offset_width;

                //调整 三个定位框的位置
                lefttopFixedView.setFixedWidth( offset_width );
                leftbottomFixedView.setFixedWidth( offset_width );
                righttopFixedView.setFixedWidth( offset_width );

                RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams)leftbottomFixedView.getLayoutParams();
                layoutParams1.setMargins( 0, 0, 0, offset_height*2 );
                leftbottomFixedView.setLayoutParams( layoutParams1 );
            }
        });
    }

    private void setFlashMode(int mode) {
        SharedPreferences sharep = getSharedPreferences("ask_camera", 0);
        Editor editor = sharep.edit();
        editor.putInt("flashmode", mode);
        editor.commit();

        if (camera == null)
            return;

        mFlashLedView.setImageResource(getImageFlashMode());

        try {
            Parameters parameters = camera.getParameters();
            if( mode == 1 ){
                parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
            }else{
                parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
            }
            camera.setParameters(parameters);
        } catch (Exception e) {
            AppLog.d( e.toString() );
        }
        startPreview();
    }
    
    private int getCameraFlashMode() {
        SharedPreferences sharep = getSharedPreferences("ask_camera", 0);
        return sharep.getInt("flashmode", 0);
    }
    
    private String getCameraFlashModeStr() {
        int mode = getCameraFlashMode();
        String c_mode = "";
        if (mode == 1) {
            c_mode = Parameters.FLASH_MODE_TORCH;
        } else {
            c_mode = Parameters.FLASH_MODE_OFF;
        }
        return c_mode;
    }

    private int getImageFlashMode() {
        SharedPreferences sharep = getSharedPreferences("ask_camera", 0);
        int mode = sharep.getInt("flashmode", 0);
        int img_id;
        if (mode == 1) {
            img_id = R.drawable.ic_flashlight_orange;
        } else {
            img_id = R.drawable.ic_flashlight_white;
        }
        return img_id;
    }

    private void startPreview() {
        if (camera != null && !bStartPreview) {
            camera.startPreview();
            bStartPreview = true;
        }
    }

    private void stopPreview() {
        if (camera != null && bStartPreview) {
            camera.stopPreview();
            bStartPreview = false;
        }
    }

    //only 仅仅是对焦
    private void autoFocus( boolean only, float centerX, float centerY ) {
        //
        if (camera != null&&!bAutoFocus&&bCameraReady) {
            //onlyFocuse = only;

            mFocusImageView.setMoveMargin( centerX - mFocusImageView.getWidth()/2, centerY - mFocusImageView.getHeight()/2 );
            mFocusImageView.setVisibility(View.VISIBLE);
            camera.autoFocus(autoFocusCallback);
            mFocusImageView.startZoomAndFadeOut();

            if( !only )bAutoFocus = true;
        }
    }

    private int getCameraDegree() {
        CameraInfo info = new CameraInfo();
        Camera.getCameraInfo(0, info);
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (rotation) {
        case Surface.ROTATION_0:
            degrees = 0;
            break;
        case Surface.ROTATION_90:
            degrees = 90;
            break;
        case Surface.ROTATION_180:
            degrees = 180;
            break;
        case Surface.ROTATION_270:
            degrees = 270;
            break;
        }

        int degree;
        if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
            degree = (info.orientation + degrees) % 360;
            degree = (360 - degree) % 360; // compensate the mirror
        } else { // back-facing
            degree = (info.orientation - degrees + 360) % 360;
        }

        return degree;
    }


    Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback() {
        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            // if( success ){
            mFocusImageView.sopZoomAndFadeOut();
//            if( !onlyFocuse )
//                //takePic();
//            else
            //TODO
            //    bAutoFocus = false;
            // }else{
            // mAnimationRotate.ratate();
            // camera.autoFocus( autoFocusCallback );
            // }
        }
    };
    //------------------------------------------------------------------------------------------------------
    class CameraDeamonThread extends Thread {
        long time = 0;
        int old_degree = 0;

        public void run() {
            while (true) {
                synchronized (lock) {
                    if (exit)
                        return;
                }
                try {
                    sleep(500);
                    if (camera != null) {
                        int degree = getCameraDegree();
                        long curr = System.currentTimeMillis();
                        if (curr - time > 500 && old_degree != degree) {
                            old_degree = degree;
                            camera.setDisplayOrientation(degree);
                            time = curr;
                        }
                    }
                } catch (Exception e) {
                    AppLog.d( e.toString() );
                }
            }
        }
    }



    // save pic
//    class SavePictureTask extends AsyncTask<byte[], String, String> {
//
//        @Override
//        protected String doInBackground(byte[]... params) {
//            byte[] data = null;
//            if (params!=null) {
//                data = params[0];
//            }
//            if (data == null || camera == null)
//                return null;
//
//            // 默认取camera0 的角度
//            int degree = getCameraDegree();
//
//            //旋转
//            BitmapFactory.Options options = new BitmapFactory.Options();
//            options.inPreferredConfig = Bitmap.Config.RGB_565;
//
//            Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length, options );
//            AppLog.i("gghjkjjkjk rrr  screenWidth = " + bmp.getWidth() + ",,, screenHeight = " + bmp.getHeight() );
//            if( degree!=0 ){
//                Matrix matrix = new Matrix();
//                //int width = bmp.getWidth(), height = bmp.getHeight();
//                if( bmp.getWidth() > 2000 || bmp.getHeight() > 2000 ){
//                    //matrix.postScale( 0.5f, 0.5f );
//                    //width /= 2;
//                    //height /= 2;
//                }
//                matrix.postRotate(degree);
//                Bitmap bitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
//
//                bmp.recycle();
//                bmp = bitmap;
//            }
//            String filepath = Environment.getExternalStorageDirectory().getAbsolutePath();
//            BitmapUtils.saveImage( filepath, bmp );
//            startEditPhoto( bmp );
//
//            //mFocusImageView.setVisibility( View.INVISIBLE );
//            bAutoFocus = false;
//            startPreview();
//
//            return null;
//        }
//    }

    SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {

        public void surfaceCreated(SurfaceHolder holder) {

            //默认打开后置摄像头
            int cameraCount = 0;
            CameraInfo cameraInfo = new CameraInfo();
            cameraCount = Camera.getNumberOfCameras();//得到摄像头的个数
            camera = null;

            PackageManager pm = getPackageManager();
            // FEATURE_CAMERA - 后置相机
            // FEATURE_CAMERA_FRONT - 前置相机
//            if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) && !pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
//                Log.i("camera", "non-support");
//            } else {
//                Log.i("camera", "support");
//            }

            for(int i = 0; i < cameraCount; i++   ) {
                Camera.getCameraInfo(i, cameraInfo);//得到每一个摄像头的信息
                if(cameraInfo.facing  == CameraInfo.CAMERA_FACING_BACK) {//代表摄像头的方位，CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
                    try{
                        camera = Camera.open(i);//打开当前选中的摄像头
                    }catch (Exception e){
                        AppLog.i( e.toString() );
                    }
                    break;
                }
            }

            if (camera == null) {
                Toast.makeText(mContext, "无法连接到相机,请检查相机权限是否打开", Toast.LENGTH_SHORT).show();
                setResult(RESULT_CANCELED);
                finish();
                return;
            }
            try {
                camera.setPreviewDisplay(holder);
                synchronized (lock) {
                    exit = false;
                }
                new CameraDeamonThread().start();
            } catch (IOException e) {
                AppLog.d( e.toString() );
                if (camera != null) {
                    camera.release();
                    camera = null;
                }
            }
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            if (camera != null) {
                int degree = getCameraDegree();
                camera.setDisplayOrientation(degree);

                Parameters parameters;
                try {
                    parameters = camera.getParameters();
                    parameters.setPictureFormat(ImageFormat.JPEG); // 设置图片格式
                    parameters.setFlashMode(getCameraFlashModeStr()); // 设置开启闪光灯
                    parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO); // 自动对焦

                    camera.setParameters(parameters);
                } catch (Exception e) {
                    AppLog.i( e.toString() );
                }

                startPreview();
                camera.setPreviewCallback( mPreviewCallBack );

                new Thread( null,new Runnable() {
                    
                    @Override
                    public void run() {
                        SystemClock.sleep(500);
                        bCameraReady = true;

                        //TODO
//                        mActivity.runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                autoFocus( false, centerScreenX, centerScreenY  );
//                            }
//                        });
                    }
                },"").start();
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            if (camera != null) {
                synchronized (lock) {
                    exit = true;
                }
                camera.setPreviewCallback(null) ;
                stopPreview();
                camera.release();
                camera = null;
            }
        }
    };


    //---------------------------------------------------------------------------------------
    /**
     * 设置拍照分辨率 / 预览分辨率
     */
//    private boolean setPicturePix( Point point ) {
//
//        if( camera == null )
//            return false;
//
//        // 获取照相机的参数
//        Parameters params = camera.getParameters();
//
//        //先根据屏幕尺寸 获取预览的合适尺寸
//        List<Camera.Size> previewlist = params.getSupportedPreviewSizes();
//        int pindex = getPreviewSize( previewlist );
//        if( pindex < 0 )
//            return false;
//
//        // 获取照相机支持的成像分辨率列表
//        List<Camera.Size> list = params.getSupportedPictureSizes();
//        // 从列表中获取最接近手机分辨率的下标
//        int index = getPictureSize( list );
//        if( pindex < 0 )
//            return false;
//
//        int prew = list.get(index).width;
//        int preh = list.get(index).height;
//
//        int w = list.get(index).width;
//        int h = list.get(index).height;
//
//        if( prew != w || preh != h ){
//            return false;
//        }
//
//        AppLog.i(" DetechAynscTask caamera set PictureSize w = " + w + ",,, h = " + h );
//
//        //设置参数  预览与成像参数一样
//        params.setPictureSize( w, h );
//        params.setPreviewSize( w, h );
//        camera.setParameters(params);
//
//        //输出 设置的width，高
//        point.set( h, w );
//        return true;
//    }

    private boolean setPicturePix( Point point ) {

        if( camera == null )
            return false;

        // 获取照相机的参数
        Parameters params = camera.getParameters();

        //先求出预览与成像交集的列表集合
        List<Camera.Size> dstlist = getIntersectList( params.getSupportedPreviewSizes(), params.getSupportedPictureSizes() );

        // 先根据屏幕尺寸 获取适尺寸
        int pindex = getSuitableSrceen( dstlist );
        if( pindex < 0 ){

            //取最接近屏幕的尺寸
            pindex = findNearScreenSize( dstlist, mScreenHeight, mScreenWidth );
        }
        if( pindex < 0 )
            return false;

        int w = dstlist.get(pindex).width;
        int h = dstlist.get(pindex).height;

        AppLog.i(" DetechAynscTask caamera set PictureSize w = " + w + ",,, h = " + h );

        //设置参数  预览与成像参数一样
        params.setPictureSize( w, h );
        params.setPreviewSize( w, h );
        camera.setParameters(params);

        //输出 设置的width，高
        point.set( h, w );
        return true;
    }

    /**
     * 得到两个列表的交集
     * @param previewlist  list
     * @param piclist       list
     * @return 交集列表
     */
    private List<Camera.Size> getIntersectList( List<Camera.Size> previewlist, List<Camera.Size> piclist ){
        List<Camera.Size> list = new ArrayList<>();
        for( Camera.Size size : previewlist ){
            if( hasSizeInList( size, piclist ) ){
                list.add( size );
            }
        }
        return list;
    }

    private boolean hasSizeInList( Camera.Size srcsize, List<Camera.Size> piclist ){
        for( Camera.Size size : piclist ){
            if( size.height == srcsize.height && size.width == srcsize.width )
                return true;
        }
        return false;
    }


    /**
     * 获取拍照之后的尺寸
     */
//    private int getPictureSize(List<Camera.Size> list) {
//
//        //sizes 默认是横屏，这里使用的是竖屏拍摄 --手机
//        // 屏幕的宽度
//        int screenWidth = mScreenWidth;
//        int screenHeight = mScreenHeight;
//
//        AppLog.i("-------------- ddsdsds screenWidth = " + screenWidth + ",,,, screenHeight = " + screenHeight );
//
//        if( screenWidth < screenHeight ){
//            int tmp = screenWidth;
//            screenWidth = screenHeight;
//            screenHeight = tmp;
//        }
//
//        //先查找与手机屏幕大小匹配的尺寸
//        int index = findMatchHeight( list, screenWidth, screenHeight );
//
////        //当未找到与手机分辨率相等的数值,且手机分辨率大于2000，缩小 2 倍来查找
////        if(index == -1 && screenHeight > 2000) {
////            index = findScreenSize( list, screenWidth/2, screenHeight/2 );
////        }
////
////        //如果还没有找到，按屏幕比例来
////        if( index == -1 ){
////            float rate = screenHeight * 1f / screenWidth;
////            for (int i = 0; i < list.size(); i++) {
////                Camera.Size size = list.get(i);
////                if( rate > 1 ){
////                    if( (size.width > size.height && size.width*1f/size.height==rate) || (size.width < size.height && size.height*1f/size.width==rate) )
////                        return i;
////                }else{
////                    if( (size.width < size.height && size.width*1f/size.height==rate) || (size.width > size.height && size.height*1f/size.width==rate) )
////                        return i;
////                }
////            }
////        }
//
//        //设置的预览大小应该是大于或者等于自定义的预览大小的。因此，在获得所有的预览值大小之后，可以将每一组值与自定义的预览大小值做比较，
//        // 得到宽的差的绝对值和高的差的绝对值之和，然后从中选出“宽的差的绝对值和高的差的绝对值之和”中最小的值，并且该组的宽和高都是大于
//        // 或者等于自定义预览大小的宽和高的值。
//        //if( index == -1 ) index = findNearScreenSize(  list, screenWidth, screenHeight  );
//
//        //还是没有找到，取中间
//        //if( index == -1 ) index = list.size() / 2;
//
//        return index;
//    }

    /**
     * 根据屏幕尺寸，获取合适的size
     */
    private int getSuitableSrceen(List<Camera.Size> list) {

        //sizes 默认是横屏，这里使用的是竖屏拍摄 --手机
        // 屏幕的宽度
        int screenWidth = mScreenWidth;
        int screenHeight = mScreenHeight;

        if( screenWidth < screenHeight ){
            int tmp = screenWidth;
            screenWidth = screenHeight;
            screenHeight = tmp;
        }

        int index = -1;
        Camera.Size dstsize = null;
        for (int i = 0; i < list.size(); i++) {
            Camera.Size size = list.get(i);
            if( screenWidth == size.width && size.height <= screenHeight  ) {
                if( dstsize == null ){
                    dstsize = size;
                    index = i;
                }else{
                    if( screenHeight-size.height < screenHeight-dstsize.height ){
                        dstsize = size;
                        index = i;
                    }
                }
            }
        }
        return index;
    }

    private int findNearScreenSize( List<Camera.Size> sizes, int width, int height  ){

        //先
        ArrayList<WrapCameraSize> wrapCameraSizes = new ArrayList<>(sizes.size());
        for (int i = 0; i < sizes.size(); i++) {
            Camera.Size size = sizes.get(i);

            WrapCameraSize wrapCameraSize = new WrapCameraSize();
            wrapCameraSize.setWidth(size.width);
            wrapCameraSize.setHeight(size.height);
            wrapCameraSize.setD(Math.abs((size.width - width)) + Math.abs((size.height - height)));
            wrapCameraSize.setIndex( i );

            wrapCameraSizes.add(wrapCameraSize);
        }

        //排序
        WrapCameraSize minCameraSize = Collections.min(wrapCameraSizes);

        //找到最小，且
        while ( minCameraSize.getWidth() >= width || minCameraSize.getHeight() >= height ) {
            wrapCameraSizes.remove(minCameraSize);
            //minCameraSize = null;
            if( wrapCameraSizes.size() == 0 )
                break;
            WrapCameraSize[] tarray = new WrapCameraSize[ wrapCameraSizes.size() ];
            wrapCameraSizes.toArray(tarray);
            minCameraSize = Collections.min( Arrays.asList(tarray) );
        }

        return minCameraSize.getIndex();
    }

    /**
     * Created by wangjiang on 2016/1/28.用于存储得到的相机预览大小的值，以及自定义预览大小与相机预览大小差的绝对值，以便从相机预览大小所有值中找出大于或者等于自定义预览大小最合适的值。
     */
    public class WrapCameraSize implements Comparable<WrapCameraSize> {
        private int width;//宽
        private int height;//高
        private int d;//宽的差的绝对值和高的差的绝对值之和
        private int index;      //原来的序号

        public int getIndex() {
            return index;
        }

        public void setIndex(int index) {
            this.index = index;
        }

        public int getHeight() {
            return height;
        }

        public void setHeight(int height) {
            this.height = height;
        }

        public int getWidth() {
            return width;
        }

        public void setWidth(int width) {
            this.width = width;
        }

        public int getD() {
            return d;
        }

        public void setD(int d) {
            this.d = d;
        }


        @Override
        public int compareTo(WrapCameraSize another) {
            if (this.d > another.d) {
                return 1;
            } else if (this.d < another.d) {
                return -1;
            }
            return 0;
        }
    }

}
